import pinia from '@/stores'

import {
	useUserinfoStore
} from '@/stores/userinfo'
const userinfoStore = useUserinfoStore(pinia);

export default {
	// 接口地址公用部分
	ajaxUrl: "https://cartons.junwuculture.cn/prod-api",
	// ajaxUrl: "http://192.168.31.202/dev-api",
	// 网络请求
	ajax: function(method, url, data) {
		return new Promise((resolve, reject) => {
			let header = {};
			if (data.ajaxType == "form") {
				// 传给后台表单数据
				header = {
					'content-type': 'application/x-www-form-urlencoded',
				};
			} else {
				// 传给后台json数据
				header = {
					'content-type': 'application/json',
				};
			}
			header.Authorization = userinfoStore.userinfo.token;
			// 如果传过来的url不是一个完整的接口，就拼接上公用部分
			if (url.substring(0, 4) != "http") {
				url = this.ajaxUrl + url;
			}
			uni.request({
				method: method,
				url: url,
				data: data,
				header: header,
				success: (res) => {
					if (res.statusCode == 200) {
						let code = res.data.code;
						if (code == 401) {
							// 登录过期
							reject(res.data);
						} else {
							// 成功
							resolve(res.data);
						}
					} else {
						this.tiShi("接口访问出错");
					}
				},
				fail: (err) => {
					reject(err)
				}
			});
		})
	},
	// 获取上级的角色是否为minishare
	getParentRoleFun: function(userId) {
		this.ajax("GET", "/carton/wxpay/discount", {
			parentId: userId,
		}).then((res) => {
			userinfoStore.userinfo.share = res.discount || false;
		})
	},
	// 获取用户信息
	getUserInfo: function() {
		return new Promise((resolve, reject) => {
			this.ajax("GET", "/getInfo", {}).then((res) => {
				let userinfo = res.user;
				console.log(userinfo)
				if (userinfo.userId == 268) {
					userinfo.deadlineTime = "2025-04-12 16:57:36"
				}
				// 如果有上级的id
				if (userinfo.userParentId) {
					userinfoStore.userinfo.parentId = userinfo.userParentId;
					// 获取上级的角色是否为minishare
					this.getParentRoleFun(userinfo.userParentId);
				}
				let myShare = false;
				// 如果角色总有minishare，代表可以查看我的分享
				if (res.roles.indexOf("minishare") != -1) {
					myShare = true;
				}
				userinfoStore.userinfo.myShare = myShare;
				let deadlineTime = userinfo.deadlineTime;
				userinfoStore.userinfo.openid = userinfo.userName;
				userinfoStore.userinfo.deptId = userinfo.deptId;
				userinfoStore.userinfo.userId = userinfo.userId;
				userinfoStore.userinfo.phone = userinfo.phonenumber;
				if (deadlineTime) {
					userinfoStore.userinfo.deadlineTime = deadlineTime
					deadlineTime = deadlineTime.replace(/-/g, '/');
					let activeSjc = new Date().getTime();
					let userSjc = Date.parse(deadlineTime);
					if (activeSjc > userSjc) {
						userinfoStore.userinfo.expired = true;
					} else {
						userinfoStore.userinfo.expired = false;
					}
				} else {
					userinfoStore.userinfo.deadlineTime = "";
					userinfoStore.userinfo.expired = true;
				}
				resolve(res);
			}).catch((err) => {
				reject(err)
			})
		})
	},
	// 登录
	loginFun: function(code) {
		return new Promise((resolve, reject) => {
			this.ajax("POST", "/wx/user/login", {
				jscode: code,
			}).then((res) => {
				let token = res.token
				this.setData("token", token)
				userinfoStore.userinfo.token = token;
				resolve(res)
			})
		})
	},
	// 添加图片
	addImg: function(length, success, auto = true) {
		// 获取本地图片的路径
		uni.chooseImage({
			count: length, // 默认9
			sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
			sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
			success: (res) => {
				// 是否自动上传
				if (auto) {
					// 显示上传动画
					this.show('图片上传中...');
					// 将新添加的图片添加到imgs_arr中
					var imgs = res.tempFilePaths;
					if (imgs.length > length) {
						imgs = imgs.slice(0, length);
					}
					// 调用上传图片的函数
					this.uploadImg(imgs, 0, success);
				} else {
					success(res);
				}
			}
		})
	},
	// oss上传要用到的信息
	ossInfo: {},
	// 上传图片
	uploadImg: async function(imgs, index, success) {
		// 如果数组长度大于下标，说明没有上传完
		if (imgs.length > index) {
			let ossInfo = this.ossInfo;
			// 如果不存在过期时间 或者 已经过期了，重新获取ossInfo
			if (!ossInfo.expire || ossInfo.expire - 60 < new Date().getTime() / 1000) {
				try {
					ossInfo = await this.ajax("GET", "/carton/oss/getPolicy", {});
					this.ossInfo = ossInfo;
				} catch (ossErr) {
					this.tiShi("OSS参数获取失败")
				}
			}
			let filePath = imgs[index];
			const fileName = filePath.split("/").pop();
			let key = ossInfo.dir + fileName;
			uni.uploadFile({
				url: ossInfo.host,
				filePath: filePath,
				name: 'file', // 必须填file。
				formData: {
					key: key,
					policy: ossInfo.policy,
					OSSAccessKeyId: ossInfo.accessid,
					signature: ossInfo.signature,
					success_action_status: 200,
				},
				success: (res) => {
					if (res.statusCode == 200) {
						let imgSrc = ossInfo.host + key;
						success(imgSrc);
					}
					// 调用上传图片的函数
					this.uploadImg(imgs, index + 1, success);
				},
				fail: (res) => {
					hide();
					this.tiShi("上传超时！");
				}
			})
		} else {
			this.hide();
		}
	},
	// 图片预览函数
	lookImg: function(current, urls) {
		uni.previewImage({
			current: current, // 当前显示图片的https链接
			urls: urls // 需要预览的图片https链接列表
		})
	},
	// 显示加载动画
	show: function(title = "加载中...", mask = true) {
		uni.showLoading({
			title: title,
			mask: mask,
		})
	},
	// 关闭加载动画
	hide: function() {
		uni.hideLoading();
	},
	// 提示框
	tiShi: function(title, mask = false, time = 1500, icon = "none") {
		uni.showToast({
			// 提示的内容
			title: title,
			// 提示的时间
			duration: time,
			// 是否显示透明蒙层，防止触摸穿透(false)
			mask: mask,
			// 图标(success)
			icon: icon,
		})
	},
	// 对话框
	duiHua: function(obj) {
		let showCancel = true;
		if (obj.lShow == false) {
			showCancel = false;
		}
		uni.showModal({
			// 对话框的标题(选填)
			title: obj.title || "",
			// 对话框的内容(选填)
			content: obj.content || "",
			// 是否显示左边的按钮(选填，默认显示)
			showCancel: showCancel,
			// 左边按钮的文字内容(选填，默认取消)
			cancelText: obj.lText || "取消",
			// 左边按钮的文字颜色(选填，默认#000000)
			cancelColor: obj.lColor || "#000000",
			// 右边按钮的文字内容(选填，默认确定)
			confirmText: obj.rText || "确定",
			// 右边按钮的文字颜色(选填，默认#3cc51f)
			confirmColor: obj.rColor || "#3cc51f",
			success: function(res) {
				if (res.confirm) { // 点击了确定按钮
					if (obj.rFun) {
						obj.rFun();
					}
				} else { // 点击了取消按钮
					if (obj.lFun) {
						obj.lFun();
					}
				}
			}
		})
	},
	// 显示菜单
	menu: function(list, key, success, fail) {
		let arr = [];
		if (key) {
			list.forEach((obj) => {
				arr.push(obj[key]);
			})
		} else {
			arr = list;
		}
		uni.showActionSheet({
			itemList: arr,
			success: function(res) {
				let index = res.tapIndex;
				success(list[index]);
			},
			fail: function(res) {
				if (fail) {
					fail(res);
				}
			}
		});
	},
	// 打开一个新页面
	open: function(url) {
		uni.navigateTo({
			url: url
		})
	},
	// 关闭所有页面，然后打开一个新页面
	openNew: function(url) {
		uni.reLaunch({
			url: url
		});
	},
	// 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
	openTab: function(url) {
		uni.switchTab({
			url: url
		});
	},
	// 当前页打开新页面
	href: function(url) {
		uni.redirectTo({
			url: url
		})
	},
	// 页面返回
	back: function(delta = 1, success) {
		let pages = getCurrentPages();
		if (pages.length == 1) {
			if (success) {
				success();
			} else {
				this.openTab("/pages/index/index");
			}
		} else {
			uni.navigateBack({
				delta: delta - 0
			})
		}
	},
	// 将数据存到本地
	setData: function(key, data) {
		uni.setStorageSync(key, data);
	},
	// 从本地获取数据
	getData: function(key) {
		return uni.getStorageSync(key);
	},
	// 同步删除本地数据
	removeData: function(key) {
		uni.removeStorageSync(key);
	},
	// 同步清除本地数据
	clearData: function() {
		uni.clearStorage();
	},
	// 非空验证
	isText: function(text) {
		// 是否正确(默认不正确)
		let br = false;
		if (/\S/.test(text)) {
			br = true;
		}
		return br;
	},
	// 手机号验证
	isPhone: function(phone) {
		let br = false;
		if (/^[1][3,4,5,7,8,9][0-9]{9}$/.test(phone)) {
			br = true;
		}
		return br;
	},
	// 邮箱验证
	isEmail: function(email) {
		// 是否正确(默认不正确)
		let br = false;
		if (/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test(email)) {
			br = true;
		}
		return br;
	},
	// 密码验证
	isPassword: function(password) {
		// 是否正确(默认正确)
		let br = true;
		if (!(/^[a-zA-Z0-9]{6,12}$/.test(password))) {
			br = false
		}
		if (!(/^(?![^a-zA-Z]+$)(?!\D+$)/.test(password))) {
			br = false
		}
		return br
	},
	// 身份证验证
	isIdCard: function(code) {
		//身份证号合法性验证  
		//支持15位和18位身份证号  
		//支持地址编码、出生日期、校验位验证  
		var city = {
			11: "北京",
			12: "天津",
			13: "河北",
			14: "山西",
			15: "内蒙古",
			21: "辽宁",
			22: "吉林",
			23: "黑龙江 ",
			31: "上海",
			32: "江苏",
			33: "浙江",
			34: "安徽",
			35: "福建",
			36: "江西",
			37: "山东",
			41: "河南",
			42: "湖北 ",
			43: "湖南",
			44: "广东",
			45: "广西",
			46: "海南",
			50: "重庆",
			51: "四川",
			52: "贵州",
			53: "云南",
			54: "西藏 ",
			61: "陕西",
			62: "甘肃",
			63: "青海",
			64: "宁夏",
			65: "新疆",
			71: "台湾",
			81: "香港",
			82: "澳门",
			91: "国外 "
		};
		var br = true;
		var msg = "验证成功";
		if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/.test(code)) {
			br = false;
			msg = "被保人身份证号格式错误";
		} else if (!city[code.substr(0, 2)]) {
			br = false;
			msg = "被保人身份证号地址编码错误";
		} else {
			//18位身份证需要验证最后一位校验位  
			if (code.length == 18) {
				code = code.split('');
				//∑(ai×Wi)(mod 11)  
				//加权因子  
				var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
				//校验位  
				var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
				var sum = 0;
				var ai = 0;
				var wi = 0;
				for (var i = 0; i < 17; i++) {
					ai = code[i];
					wi = factor[i];
					sum += ai * wi;
				}
				if (parity[sum % 11] != code[17].toUpperCase()) {
					br = false;
					msg = "被保人身份证号校验位错误";
				}
			}
		}
		return {
			br,
			msg
		};
	},
	// 获取位置信息
	getAddress: function(success) {
		uni.authorize({
			scope: 'scope.userLocation',
			success: (res) => {
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: (res) => {
						this.setData("location", res);
						success(res);
					},
					fail: (res) => {
						let msg =
							"getLocation:fail 频繁调用会增加电量损耗，可考虑使用 wx.onLocationChange 监听地理位置变化";
						if (res.errMsg == msg) {
							success(this.getData("location"));
						} else {
							this.duiHua({
								content: "请开启GPS后等几秒再试试",
								lShow: false,
								rFun: () => {}
							});
						}
					},
				});
			},
			fail: (res) => {
				if (res.errMsg != "authorize:fail auth deny") {
					this.duiHua({
						content: "请授权获取位置信息",
						rText: "去授权",
						rFun: () => {
							uni.openSetting({
								success: (res) => {}
							});
						}
					});
				}
			}
		})
	},
	// 打开地图选择位置
	chooseAddress: function(success) {
		uni.chooseLocation({
			success: function(res) {
				success({
					// 地点名称
					name: res.name,
					// 详细地址
					address: res.address,
					// 经纬度
					lng: res.longitude,
					lat: res.latitude
				});
			},
		});
	},
	// 打开地图
	openMap: function(lng, lat, name) {
		uni.openLocation({
			longitude: lng - 0,
			latitude: lat - 0,
			name: name,
		})
	},
	// 复制
	copyFun: function(text) {
		// #ifdef APP-PLUS || MP
		uni.setClipboardData({
			data: text,
			success: function() {
				this.tiShi("复制成功");
			}
		});
		// #endif
		// #ifdef H5
		// 如果是H5，获取设备信息
		uni.getSystemInfo({
			success: (res) => {
				let input = document.createElement('input');
				input.type = 'text';
				input.value = text;
				input.style.position = 'fixed';
				input.style.top = "-100vh";
				input.style.left = "-100vw";
				input.style.opacity = 0;
				window.document.body.appendChild(input);
				input.select();
				if (res.platform == "ios") {
					input.setSelectionRange(0, input.value.length), document.execCommand('Copy');
				} else {
					document.execCommand("Copy");
				}
				document.body.removeChild(input);
				this.tiShi("复制成功");
			}
		});
		// #endif
	},
	// 清空Obj
	clearObj: function(obj) {
		const newObj = {};
		Object.keys(obj).forEach((item) => {
			newObj[item] = "";
		});
		Object.assign(obj, newObj);
	},
	// 分享配置
	getShareObjFun: function() {
		return {
			title: '纸箱包装行业报价小助手',
			path: '/pages/index/index?userId=' + userinfoStore.userinfo.userId || "",
		}
	}
}